from datetime import datetime
from django.db import transaction
from .models import StockIn, StockOut, StockRecord, StockCheck, StockCheckDetail, StockTransfer, StockTransferDetail

def generate_stock_in_no():
    """生成入库单号"""
    prefix = 'RK'
    date = datetime.now().strftime('%Y%m%d')
    
    # 获取当天的最大单号
    max_no = StockIn.objects.filter(
        stock_in_no__startswith=f'{prefix}{date}'
    ).order_by('-stock_in_no').first()
    
    if max_no:
        # 提取序号并加1
        sequence = int(max_no.stock_in_no[-4:]) + 1
    else:
        sequence = 1
    
    # 生成新的单号
    return f'{prefix}{date}{sequence:04d}'

def generate_stock_out_no():
    """生成出库单号"""
    prefix = 'CK'
    date = datetime.now().strftime('%Y%m%d')
    
    # 获取当天的最大单号
    max_no = StockOut.objects.filter(
        stock_out_no__startswith=f'{prefix}{date}'
    ).order_by('-stock_out_no').first()
    
    if max_no:
        # 提取序号并加1
        sequence = int(max_no.stock_out_no[-4:]) + 1
    else:
        sequence = 1
    
    # 生成新的单号
    return f'{prefix}{date}{sequence:04d}'

def generate_stock_check_no():
    """生成盘点单号"""
    prefix = 'PD'
    date = datetime.now().strftime('%Y%m%d')
    
    # 获取当天的最大单号
    max_no = StockCheck.objects.filter(
        check_no__startswith=f'{prefix}{date}'
    ).order_by('-check_no').first()
    
    if max_no:
        # 提取序号并加1
        sequence = int(max_no.check_no[-4:]) + 1
    else:
        sequence = 1
    
    # 生成新的单号
    return f'{prefix}{date}{sequence:04d}'

def generate_stock_transfer_no():
    """生成调拨单号"""
    prefix = 'DB'
    date = datetime.now().strftime('%Y%m%d')
    
    # 获取当天的最大单号
    max_no = StockTransfer.objects.filter(
        transfer_no__startswith=f'{prefix}{date}'
    ).order_by('-transfer_no').first()
    
    if max_no:
        # 提取序号并加1
        sequence = int(max_no.transfer_no[-4:]) + 1
    else:
        sequence = 1
    
    # 生成新的单号
    return f'{prefix}{date}{sequence:04d}'

def create_stock_record(product, type, quantity, before_stock, related_no, create_user, remark=None):
    """创建库存流水记录"""
    after_stock = before_stock + quantity if type in [1, 3] else before_stock - quantity
    return StockRecord.objects.create(
        product=product,
        type=type,
        quantity=quantity,
        before_stock=before_stock,
        after_stock=after_stock,
        related_no=related_no,
        create_user=create_user,
        remark=remark
    )

@transaction.atomic
def update_stock_in_status(stock_in, new_status, create_user):
    """更新入库单状态"""
    if stock_in.status == new_status:
        return False, '状态未改变'
    
    if new_status == 1:  # 审核通过
        # 检查是否已经审核过
        if stock_in.status == 1:
            return False, '该入库单已经审核通过'
        
        # 更新商品库存并创建流水记录
        for detail in stock_in.details.all():
            product = detail.product
            before_stock = product.stock
            product.stock += detail.quantity
            product.save()
            
            # 创建入库流水记录
            create_stock_record(
                product=product,
                type=1,
                quantity=detail.quantity,
                before_stock=before_stock,
                related_no=stock_in.stock_in_no,
                create_user=create_user,
                remark=f'入库单审核通过，入库{detail.quantity}件'
            )
    
    stock_in.status = new_status
    stock_in.save()
    return True, None

@transaction.atomic
def update_stock_out_status(stock_out, new_status, create_user):
    """更新出库单状态"""
    if stock_out.status == new_status:
        return False, '状态未改变'
    
    if new_status == 1:  # 审核通过
        # 检查是否已经审核过
        if stock_out.status == 1:
            return False, '该出库单已经审核通过'
        
        # 检查库存是否充足
        for detail in stock_out.details.all():
            product = detail.product
            if product.stock < detail.quantity:
                return False, f'商品 {product.name} 库存不足'
        
        # 更新商品库存并创建流水记录
        for detail in stock_out.details.all():
            product = detail.product
            before_stock = product.stock
            product.stock -= detail.quantity
            product.save()
            
            # 创建出库流水记录
            create_stock_record(
                product=product,
                type=2,
                quantity=detail.quantity,
                before_stock=before_stock,
                related_no=stock_out.stock_out_no,
                create_user=create_user,
                remark=f'出库单审核通过，出库{detail.quantity}件'
            )
    
    stock_out.status = new_status
    stock_out.save()
    return True, None

@transaction.atomic
def update_stock_check_status(stock_check, new_status, create_user):
    """更新盘点单状态"""
    if stock_check.status == new_status:
        return False, '状态未改变'
    
    if new_status == 1:  # 审核通过
        # 检查是否已经审核过
        if stock_check.status == 1:
            return False, '该盘点单已经审核通过'
        
        # 更新商品库存并创建流水记录
        for detail in stock_check.details.all():
            product = detail.product
            before_stock = product.stock
            product.stock = detail.actual_stock
            product.save()
            
            # 创建盘点流水记录
            create_stock_record(
                product=product,
                type=3,
                quantity=detail.difference,
                before_stock=before_stock,
                related_no=stock_check.check_no,
                create_user=create_user,
                remark=f'盘点单审核通过，差异{detail.difference}件'
            )
    
    stock_check.status = new_status
    stock_check.save()
    return True, None

@transaction.atomic
def update_stock_transfer_status(stock_transfer, new_status, create_user):
    """更新调拨单状态"""
    if stock_transfer.status == new_status:
        return False, '状态未改变'
    
    if new_status == 1:  # 审核通过
        # 检查是否已经审核过
        if stock_transfer.status == 1:
            return False, '该调拨单已经审核通过'
        
        # 检查调出仓库库存是否充足
        for detail in stock_transfer.details.all():
            product = detail.product
            if product.stock < detail.quantity:
                return False, f'商品 {product.name} 在调出仓库库存不足'
        
        # 更新商品库存并创建流水记录
        for detail in stock_transfer.details.all():
            product = detail.product
            before_stock = product.stock
            product.stock -= detail.quantity
            product.save()
            
            # 创建调出流水记录
            create_stock_record(
                product=product,
                type=4,
                quantity=-detail.quantity,
                before_stock=before_stock,
                related_no=stock_transfer.transfer_no,
                create_user=create_user,
                remark=f'调拨单审核通过，从{stock_transfer.from_warehouse}调出{detail.quantity}件'
            )
            
            # 创建调入流水记录
            create_stock_record(
                product=product,
                type=4,
                quantity=detail.quantity,
                before_stock=before_stock - detail.quantity,
                related_no=stock_transfer.transfer_no,
                create_user=create_user,
                remark=f'调拨单审核通过，调入{stock_transfer.to_warehouse}{detail.quantity}件'
            )
    
    stock_transfer.status = new_status
    stock_transfer.save()
    return True, None 